package com.bom_samaritano.dao;

import java.util.ArrayList;
import java.util.Collection;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class PersonDAO extends SQLiteOpenHelper {

	public PersonDAO(Context context, String name, CursorFactory factory,
			int version) {
		super(context, Person.TABLE, factory, Person.VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

		db.execSQL("CREATE TABLE IF NOT EXISTS "
				+ Person.TABLE
				+ " ( id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR NULL, email VARCHAR NULL, phone VARCHAR NULL, "
				+ "vacancy INTEGER UNSIGNED NULL, hascar BIT NULL, PRIMARY KEY(id) );");
	}

	public void inserir(Person person) {
		ContentValues valores = new ContentValues();
		valores.put(Person.COL_NAME, person.getName());
		valores.put(Person.COL_EMAIL, person.getEmail());
		valores.put(Person.COL_PHONE, person.getPhone());
		valores.put(Person.COL_VACANCY, person.getVacancy());
		valores.put(Person.COL_HAS_CAR, person.isHascar() ? 0 : 1);

		getWritableDatabase().insert(Person.TABLE, null, valores);
	}

	public Collection<Person> getLista() {
		Cursor c = getWritableDatabase()
				.query(Person.TABLE,
						new String[] { Person.COL_ID, Person.COL_NAME,
								Person.COL_PHONE }, null, null, null, null,
						null);
		Collection<Person> lista = new ArrayList<Person>();
		while (c.moveToNext()) {
			Person person = new Person();
			person.setId(c.getInt(0));
			person.setName(c.getString(1));
			person.setPhone(c.getString(2));

			lista.add(person);
		}
		c.close();

		return lista;

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		throw new UnsupportedOperationException();
		// db.execSQL("DROP TABLE IF EXISTS " + TABLE_PERSON);
		// db.execSQL("DROP TABLE IF EXISTS " + TABLE_ROUTE);
		// onCreate(db);
	}
}
